import { Component } from '@angular/core'
import {
  IonicPage,
  NavController,
  NavParams,
  ToastController
} from 'ionic-angular'
import { Storage } from '@ionic/storage'

import { HttpServicesProvider } from '../../providers/http-services/http-services'
import { ConfigsProvider } from '../../providers/configs/configs'
// import { Md5 } from 'ts-md5/dist/md5'

import { TabsPage } from '../tabs/tabs'

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  loginfo: { account: string; password: string } = {
    account: '',
    password: ''
  }

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private local_storage: Storage,
    private httpService: HttpServicesProvider,
    private configs: ConfigsProvider,
    private toastCtrl: ToastController
  ) {
    // console.log('0', ' controler')
    // console.log(Md5.hashStr('11111111J2Uc5pOojLlw').toString())
  }

  doLogin() {
    // let data = new FormData()
    // data.append('username', this.loginfo.account)
    // data.append('password', this.loginfo.password)
    let data = {}
    data['username'] = this.loginfo.account
    data['password'] = this.loginfo.password
    this.httpService.requestDataLoginPost(
      'app/login',
      data,
      {},
      (status, datas) => {
        if (status) {
          if (datas['msg'] == 'success') {
            this.navCtrl.setRoot(
              TabsPage,
              {},
              {
                animate: true,
                direction: 'forward'
              }
            )
            this.local_storage.set('token', datas.token)
            this.local_storage.set('user', datas.user)
          } else {
            this.presentToast(datas.message)
          }
        }
      }
    )
  }

  presentToast(message) {
    let toast = this.toastCtrl.create({
      message: message,
      duration: 2000,
      position: 'middle'
    })

    toast.onDidDismiss(() => {})

    toast.present()
  }
}
